package com.qdxwx.web.controller.user;


import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserLetter;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 个人中心  Controller
 * @author developer
 */
@Controller
@RequestMapping("/user")
public class UserLetterController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(UserLetterController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private UserLetterService userLetterService;

	/**
	 * 查询站内信收件箱（无社区）
	 */
	@RequestMapping(value = "/letter.html")
	public String queryUserLetter(HttpServletRequest request, ModelMap model) {
		User user = LoginUser.getUser(request);
		if (user == null) {
			return VIEW_ERROR_403;
		}

		PageRequest page = PageRequest.form(request);
		page.setPageSize(12);// 分页页数为12

		UserLetter userLetter = new UserLetter();
		userLetter.setUserId(user.getUserId());// set用户id

		List<UserLetter> letterList = userLetterService.getUserInbox(user, page);// 查询站内信收件箱

		int total = userLetterService.count(userLetter);

		model.put("totalPages", page.getTotalPages(total));

		// 更新所有收件箱为已读
		userLetterService.updateRead(userLetter);
		//修改用户消息数后  重新加入缓存
		user.setLetterCount(0);

		LoginUser.setUser(request, user);

		model.put("letterList", letterList);// 查询出的站内信放入modelAndView中
		model.put("page", page);// 分页参数放入modelAndView中
		model.put("user", LoginUser.getUser(request));
		if(TKRequest.isMobileBrowse(request)){
			return getViewPathH5("user/uc-letter-inbox");
		}
		return getViewPath("ucenter/uc-letter-inbox");
	}

	/**
	 * 删除站内信收件箱
	 */
	@RequestMapping(value = "/ajax/delLetterInbox")
	@ResponseBody
	public AjaxResult delLetterInbox(HttpServletRequest request) {
		long letterId = TKConvert.toLong(request.getParameter("id"));
		long userId = LoginUser.getUserId(request);// set 用户id
		if (letterId == 0 || userId == 0) {
			return AjaxResult.error("参数异常!");
		}
		UserLetter userLetter = userLetterService.get(letterId);
		if (userLetter.getUserId() != userId) {
			return AjaxResult.error("非法操作");
		}
		int num = userLetterService.delete(letterId, userId);// 删除收件箱
		return num > 0 ? AjaxResult.success() : AjaxResult.error("删除失败，请稍后再试");
	}

	/**
	 * 更改系统消息为已读
	 */
	@RequestMapping(value = "/ajax/changeStatus")
	@ResponseBody
	public AjaxResult changeStatus(HttpServletRequest request) {
		try {
			long letterId = TKConvert.toLong(request.getParameter("id"));
			long userId = LoginUser.getUserId(request);
			UserLetter userLetter = userLetterService.get(letterId);
			if (userLetter == null) {
				return AjaxResult.error("not found!");
			}
			if (userLetter.getUserId() != userId) {
				return AjaxResult.error("not found!");
			}
			userLetter.setUserId(userId);// set 用户id
			userLetterService.delete(letterId, userId);
			return AjaxResult.success();
		} catch (Exception e) {
			logger.error("UserController.changeStatus()", e);
			return AjaxResult.error(e.getMessage());
		}
	}

}